package crossrun.tool.pdf2img.view;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import crossrun.tool.pdf2img.R;
import crossrun.tool.pdf2img.ui.main.CacheFileViewModel;
import crossrun.tool.pdf2img.util.FileUtils;

public class FileItemView extends LinearLayout {
    TextView nameTxt,pathTxt,timeTxt;
    File file;
    String index;
    String[] ope;


    public FileItemView(Context context) {
        super(context);
        inflate(context, R.layout.item_file, this);
        nameTxt = findViewById(R.id.file_name);
        pathTxt = findViewById(R.id.file_path);
        timeTxt = findViewById(R.id.file_create_time);
        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(getContext(),R.style.Dialog_Alert_Self)
                        .setTitle("操作")
                        .setItems(ope, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String o = ope[which];
                                if ("删除".equals(o)) {
                                    Log.e("top1", o);
                                    CacheFileViewModel cacheFileViewModel = new ViewModelProvider(((AppCompatActivity) getContext())).get(CacheFileViewModel.class);
                                    cacheFileViewModel.deleteFile(file, index);
                                } else if ("分享".equals(o)) {
                                    FileUtils.shareFile(getContext(), file);
                                } else if ("打开".equals(o)) {
                                    FileUtils.openFileDir(getContext(), file);
                                }
                            }
                        }).show();
            }
        });
    }

    public void setFile(File f, String index) {
        file = f;
        nameTxt.setText(f.getName());
        pathTxt.setText(f.getAbsolutePath());
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                .format(new Date(f.lastModified()));
        timeTxt.setText(time);
        this.index = index;
        if ("from".equals(index) || "zip".equals(index)) {
            ope = new String[]{"删除", "分享"};
        } else if ("pic".equals(index)) {
            ope = new String[]{"删除"};
        } else {
            ope = new String[]{};
        }
    }
}
